﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using DC2010.Effects;
using DC2010.Events;
using DC2010.Objects.Data;
using EventInfo = DC2010.Objects.Data.EventInfo;

namespace DC2010.Systems
{
    public class EventSystem : BaseSystem<EventInfo, EventGfx, EventData>
    {
        public InstancesEvents Instances { get; set; }

        public override void Init(string code)
        {
            IsUsingInfo = true;
            IsUsingData = true;
			IsUsingGfx = false;
		
		
            InfoFileName = "Data\\" + code + "Info.xml";
            GfxFileName = "Data\\" + code + "Gfx.xml";
            DataFileName = "Temp\\" + code + "Data.xml";

            Code = code;

            DateTime dtStart = DateTime.Now;
            base.Init(code);

            //prepare effects for common use
            Instances = new InstancesEvents();

            log.Info("Core, Events init takes: " + (DateTime.Now - dtStart).TotalSeconds + " seconds");
        }

        /// <summary>
        /// Method will create new instance of effect. Definition of this effect is in EffectData. EffectData 
        /// is passed as parametr to Effect.
        /// </summary>
        /// <param name="ed"></param>
        /// <returns></returns>
        public EventLogic InstantiateEvent(EventData ed)
        {
            //Effect are stored in "DC2010.Effects" namespace

            EventInfo ei = GetInfo(ed.InfoId);
            string FullName = "DC2010.Events." + ei.Method;

            if (string.IsNullOrEmpty(ei.Method)) return null;

            try
            {
                Assembly assembly = Assembly.GetCallingAssembly();
                Type type = assembly.GetType(FullName);

                object o = Activator.CreateInstance(type, ed);

                if ((o != null) && (o is EventLogic))
                {
                    //this is place where all intance are alive
                    AddData(ed);
                    return (EventLogic)o;
                }
            }
            catch (Exception)
            {
                return null;
                //log
            }

            return null;
        }

    }
}
